package com.uex.dev.manage.common.utils;

import com.uex.dev.manage.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

/**
 * @author wangc
 * @create 2023/11/4
 * @description
 */
@Slf4j
public class Md5Utils {
    private static final String[] HEX_DIGITS = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }


    public static String MD5EncodeWithSalt(String origin, String salt) {
        return encodeString(origin, salt, CommonConstant.CHARSET_UTF8);
    }

    public static String MD5EncodeWithAfterSalt(String origin, String salt) {
        return encodeString( salt,origin, CommonConstant.CHARSET_UTF8);
    }

    private static String encodeString(String origin, String salt, String charsetname) {
        String result = null;
        try {
            String newString = new String(salt+origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if ((charsetname == null) || ("".equals(charsetname))) {
                result = byteArrayToHexString(md.digest(newString
                        .getBytes()));
            } else {
                result = byteArrayToHexString(md.digest(newString
                        .getBytes(charsetname)));
            }
        } catch (Exception e) {
            log.error("encode md5 string error.", e);
        }
        return result;
    }
}
